/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils;

import java.io.IOException;
import java.util.List;
import org.jdom.Element;
import org.jdom.Text;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 *
 * @author Maciek
 */
public class SplitMessage {
    public static final String partTag = "part";
    public Element splitContent(Element parent, String message, int blocks){
         int len = message.length();
         for(int i = 0 ; i*blocks < len ; ++i){
             Element part = new Element("part");
             part.setAttribute("sequence", new Integer(i+1).toString());
             part.addContent(message.substring(i*blocks, Math.min((i+1)*blocks, len)));
             parent.addContent(part);
         }
         return parent;
    }
    
    private String duzyString(int size){
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ; i < size; ++i){
            sb.append(i);
        }
        return sb.toString();
    }
    
    public String combineMessage(Element parent){
  
        return combineMessageNaive(parent);
        
       
    }
    
    private String combineMessageNaive(Element parent){
        StringBuilder sb = new StringBuilder();
        for (int i = 1 ; ; i++){
            if(parent.getChild(partTag + i) == null) 
                break;
            sb.append(parent.getChildText(partTag + i));
            
        }
        return sb.toString();
    }
    
    public static void main(String args[]) throws Exception{
         Element certificate = new Element("Certificiate");
         SplitMessage sm = new SplitMessage();
         String start = sm.duzyString(600);
         certificate = sm.splitContent(certificate, start, 100);
         
         
         XMLOutputter outputter = new XMLOutputter();
         outputter.setFormat(Format.getPrettyFormat());
        
         try {
                outputter.output(certificate, System.out);       
         }
         catch (IOException e) {
         System.err.println(e);
        }
        String result = sm.combineMessage(certificate);
        System.out.println("result == start " + result.equals(start));
    }
}
